#include "zip.h"
#include "fs.h"
#include <string.h>
#include "dbgio.h"
error_type_t krnl_zip_error;

/** VFS based ZIP utility **/
//TODO: Make this use KSTDIO.H

void krnl_zip_set_error(error_type_t _error){
	krnl_zip_error = _error;
}

void krnl_zip_extract_to(vfs_node_t *target,void *source){
	zip_lf_hdr_t *file = (zip_lf_hdr_t *)source;
	char *filename_ptr;
	char filename[128];
	uint8_t *data_pointer;
	zip_lf_hdr_t *nxt_file;
	if (file->magic != 0x04034b50){
		dprintf("Invalid header, not PK but %x\n",file->magic);
	}		
	while (1){
		if (file->magic != 0x04034b50)
			break;
		if (file->compression != 0){
			dprintf("Compressed ZIP file, can not extract\n");
			return;
		}
		data_pointer = (uint8_t *)(((uint32_t)&(file->filename_ptr)) + file->filename_length + file->extra_field_length);
		filename_ptr = (char *) &(file->filename_ptr);
		memcpy(filename,filename_ptr,file->filename_length);
		filename[file->filename_length] = '\0';
	//	dprintf ("   expanding : %s\n",filename);
		if (filename[file->filename_length - 1] == '/'){
			filename[file->filename_length - 1] = '\0';
			mkdir_rc_fs(target,filename,0x1FF);
		}else {
			write_fs(touch_rc_fs(target,filename,0x1FF),data_pointer,0,file->compressed_size,0);
		}
		nxt_file = (zip_lf_hdr_t *)(((uint32_t)data_pointer) + file->compressed_size);
		file = nxt_file;
	}
}